package net.magicalcloud.magicalcloud.view.viewImpl.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.nightonke.boommenu.BoomButtons.BoomButton;
import com.nightonke.boommenu.BoomButtons.ButtonPlaceEnum;
import com.nightonke.boommenu.BoomButtons.OnBMClickListener;
import com.nightonke.boommenu.BoomButtons.SimpleCircleButton;
import com.nightonke.boommenu.BoomButtons.TextInsideCircleButton;
import com.nightonke.boommenu.BoomButtons.TextOutsideCircleButton;
import com.nightonke.boommenu.BoomMenuButton;
import com.nightonke.boommenu.ButtonEnum;
import com.nightonke.boommenu.OnBoomListener;
import com.nightonke.boommenu.Piece.PiecePlaceEnum;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import net.magicalcloud.magicalcloud.R;
import net.magicalcloud.magicalcloud.adapter.CloudFilesAdapter;
import net.magicalcloud.magicalcloud.adapter.VagueSearchFileAdapter;
import net.magicalcloud.magicalcloud.base.BaseFragment;
import net.magicalcloud.magicalcloud.entity.Files;
import net.magicalcloud.magicalcloud.listener.OnRecyclerViewListener;
import net.magicalcloud.magicalcloud.presenter.CloudPresenter;
import net.magicalcloud.magicalcloud.util.BuilderManager;
import net.magicalcloud.magicalcloud.view.ICloudView;
import net.magicalcloud.magicalcloud.view.viewImpl.activity.MainActivity;
import net.magicalcloud.magicalcloud.view.viewImpl.activity.MediaPlayerActivity;
import net.magicalcloud.magicalcloud.view.viewImpl.activity.RecycleActivity;
import net.magicalcloud.magicalcloud.view.viewImpl.activity.TransferActivity;
import net.magicalcloud.magicalcloud.view.viewImpl.activity.VagueSearchActivity;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.nightonke.boommenu.ButtonEnum.TextInsideCircle;

/**
 * 第一页 云盘
 * Created by Pei on 2018/6/7.
 */

public class CloudFragment extends BaseFragment<ICloudView,CloudPresenter> implements ICloudView {

    private View view;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.sw_refresh)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.bmb_category)
    BoomMenuButton bmbCategory;
    @BindView(R.id.bmb_option)
    BoomMenuButton bmbOption;


    private CloudFilesAdapter adapter;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_cloud, container, false);
        //绑定ButterKnife
        ButterKnife.bind(this,view);
        //初始化view
        initView();



        return view;
    }



    void initView(){
        adapter=new CloudFilesAdapter();
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(adapter);

        adapter.setOnRecyclerViewListener(new OnRecyclerViewListener() {
            @Override
            public void onItemClick(View v, int position) {
                if(adapter.getItem(position).getFiletypeId()==9){
                    Bundle bundle=new Bundle();
                    bundle.putString("videoUrl",adapter.getItem(position).getUrl());
                    bundle.putString("videoTitle",adapter.getItem(position).getFileName());
                    startActivity(MediaPlayerActivity.class,bundle);
                }
                if(adapter.getItem(position).getFiletypeId()==5){
                    query(mPresenter.TYPE_FORWARD,adapter.getItem(position).getFileId());
                }
            }

            @Override
            public boolean onItemLongClick(View v, int position) {
                //toast("长按了"+adapter.getItem(position).getFileName());
                if(adapter.getItem(position).getFiletypeId()!=5){
                    Bundle bundle=new Bundle();
                    bundle.putSerializable("data",adapter.getItem(position));
                    startActivity(TransferActivity.class,bundle);
                }

                return false;
            }
        });
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                query(mPresenter.TYPE_REFRESH,null);
            }
        });
        //第一次进入根文件先查询根目录下的文件
        query(mPresenter.TYPE_FORWARD,null);



        bmbCategory.setButtonEnum(TextInsideCircle);
        bmbCategory.setPiecePlaceEnum(PiecePlaceEnum.DOT_6_4);
        bmbCategory.setButtonPlaceEnum(ButtonPlaceEnum.SC_6_4);

        bmbOption.setButtonEnum(TextInsideCircle);
        bmbOption.setPiecePlaceEnum(PiecePlaceEnum.DOT_4_1);
        bmbOption.setButtonPlaceEnum(ButtonPlaceEnum.SC_4_1);

        addBuilder1();
        addBuilder2();

    }
    private void addBuilder1() {
        bmbCategory.setOnBoomListener(new OnBoomListener() {
            @Override
            public void onClicked(int index, BoomButton boomButton) {

            }

            @Override
            public void onBackgroundClick() {

            }

            @Override
            public void onBoomWillHide() {

            }

            @Override
            public void onBoomDidHide() {
                bmbOption.setVisibility(View.VISIBLE);
            }

            @Override
            public void onBoomWillShow() {

            }

            @Override
            public void onBoomDidShow() {

            }
        });
        bmbCategory.addBuilder(new TextInsideCircleButton.Builder()
                .normalImageRes(R.drawable.type_video)
                .normalText("视频")
                .listener(new OnBMClickListener() {
                    @Override
                    public void onBoomButtonClick(int index) {
                        //toast("点击了视频"+index);
                    }
                }));
        bmbCategory.addBuilder(new TextInsideCircleButton.Builder()
                .normalImageRes(R.drawable.type_picture)
                .normalText("图片")
                .listener(new OnBMClickListener() {
                    @Override
                    public void onBoomButtonClick(int index) {
                        //toast("点击了图片"+index);
                    }
                }));
        bmbCategory.addBuilder(new TextInsideCircleButton.Builder()
                .normalImageRes(R.drawable.type_documnet)
                .normalText("文档")
                .listener(new OnBMClickListener() {
                    @Override
                    public void onBoomButtonClick(int index) {
                        //toast("点击了文档"+index);
                    }
                }));
        bmbCategory.addBuilder(new TextInsideCircleButton.Builder()
                .normalImageRes(R.drawable.type_music)
                .normalText("音乐")
                .listener(new OnBMClickListener() {
                    @Override
                    public void onBoomButtonClick(int index) {
                        //toast("点击了音乐"+index);
                    }
                }));
        bmbCategory.addBuilder(new TextInsideCircleButton.Builder()
                .normalImageRes(R.drawable.type_app)
                .normalText("应用")
                .listener(new OnBMClickListener() {
                    @Override
                    public void onBoomButtonClick(int index) {
                        //toast("点击了其它"+index);
                    }
                }));
        bmbCategory.addBuilder(new TextInsideCircleButton.Builder()
                .normalImageRes(R.drawable.type_others)
                .normalText("其它")
                .listener(new OnBMClickListener() {
                    @Override
                    public void onBoomButtonClick(int index) {
                        //toast("点击了其它"+index);
                    }
                }));


    }
    private void addBuilder2() {
        bmbOption.addBuilder(new TextInsideCircleButton.Builder()
                .normalImageRes(R.drawable.type_video)
                .normalText("上传")
                .listener(new OnBMClickListener() {
                    @Override
                    public void onBoomButtonClick(int index) {
                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                        //intent.setType(“image/*”);//选择图片
                        //intent.setType(“audio/*”); //选择音频
                        //intent.setType(“video/*”); //选择视频 （mp4 3gp 是android支持的视频格式）
                        //intent.setType(“video/*;image/*”);//同时选择视频和图片
                        intent.setType("*/*");//无类型限制
                        intent.addCategory(Intent.CATEGORY_OPENABLE);
                        startActivityForResult(intent, 1);
                    }
                }));
        bmbOption.addBuilder(new TextInsideCircleButton.Builder()
                .normalImageRes(R.drawable.type_video)
                .normalText("搜索")
                .listener(new OnBMClickListener() {
                    @Override
                    public void onBoomButtonClick(int index) {
                        startActivity(VagueSearchActivity.class,null);
                    }
                }));
        bmbOption.addBuilder(new TextInsideCircleButton.Builder()
                .normalImageRes(R.drawable.type_video)
                .normalText("分类")
                .listener(new OnBMClickListener() {
                    @Override
                    public void onBoomButtonClick(int index) {
                        toast("点击了分类"+index);
                        bmbCategory.boom();
                        bmbOption.setVisibility(View.GONE);
                    }
                }));

        bmbOption.addBuilder(new TextInsideCircleButton.Builder()
                .normalImageRes(R.drawable.type_video)
                .normalText("回收站")
                .listener(new OnBMClickListener() {
                    @Override
                    public void onBoomButtonClick(int index) {

                        startActivity(RecycleActivity.class,null);

                    }
                }));
    }



    @OnClick(R.id.btn_back)
    void back(){
        //返回上一层
        query(mPresenter.TYPE_BACK,null);
    }

    @OnClick(R.id.bmb_category)
    void showcategory(){
        bmbCategory.setButtonEnum(ButtonEnum.SimpleCircle);
        bmbCategory.setPiecePlaceEnum(PiecePlaceEnum.DOT_1);
        bmbCategory.setButtonPlaceEnum(ButtonPlaceEnum.SC_1);
        bmbCategory.addBuilder(BuilderManager.getSimpleCircleButtonBuilder());
    }

    //请求获取数据
    private void query(int type,String fileId){
        mPresenter.requestSubfile(type,fileId);
    }

    @Override
    public void setRecycleViewData(List<Files> files) {
        adapter.updateData(files);
        smartRefreshLayout.finishRefresh();
    }

    @Override
    protected CloudPresenter createPresenter() {
        return new CloudPresenter();
    }











    String path;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            if ("file".equalsIgnoreCase(uri.getScheme())){//使用第三方应用打开
                path = uri.getPath();
                //tv.setText(path);

                //Toast.makeText(getContext(),path+"11111",Toast.LENGTH_SHORT).show();
                return;
            }
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后
                path = getPath(getContext(), uri);
                //tv.setText(path);
                String[] paths={path};
                Toast.makeText(getContext(),path,Toast.LENGTH_SHORT).show();
                mPresenter.uploadFile(paths);
            } else {//4.4以下下系统调用方法
                path = getRealPathFromURI(uri);
                //tv.setText(path);
                //Toast.makeText(getContext(), path+"222222", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public String getRealPathFromURI(Uri contentUri) {
        String res = null;
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContext().getContentResolver().query(contentUri, proj, null, null, null);
        if(null!=cursor&&cursor.moveToFirst()){;
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
            cursor.close();
        }
        return res;
    }

    /**
     * 专为Android4.4设计的从Uri获取文件绝对路径，以前的方法已不好使
     */
    @SuppressLint("NewApi")
    public String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public String getDataColumn(Context context, Uri uri, String selection,
                                String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    @Override
    public void uploadResult(boolean result) {
        if(result){
            toast("上传成功");
        }else{
            toast("上传失败");
        }
    }

}
